package com.yehangtech.designpattern.结构型_适配器.adapter;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.yehangtech.designpattern.结构型_适配器.mq.RebateInfo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;

public class MqAdapter {
    public static RebateInfo filter(String strJson, Map<String, String> map) throws InvocationTargetException, IllegalAccessException {
        return doFilter(JSONUtil.toBean(strJson, Map.class), map);
    }

    public static RebateInfo doFilter(Map<String, Object> jsonMap, Map<String, String> map) throws InvocationTargetException, IllegalAccessException {
        RebateInfo rebateInfo = new RebateInfo();
        Class<? extends RebateInfo> rebateInfoClass = rebateInfo.getClass();
        Method[] rebateInfoMethodArray = rebateInfoClass.getMethods();
        for (String rebateInfoParam : map.keySet()) {
            String rebateInfoValue = map.get(rebateInfoParam);
            Object value = jsonMap.get(rebateInfoValue);
            String methodName = "set" + StrUtil.upperFirst(rebateInfoParam);
            for (Method method : rebateInfoMethodArray) {
                if (method.getName().equals(methodName)) {
                    try {
                        method.invoke(rebateInfo, value);
                    } catch (Exception e) {
                        Class<?>[] parameterTypes = method.getParameterTypes();
                        if (parameterTypes[0].equals(Date.class)) {
                            method.invoke(rebateInfo, new Date(Long.parseLong(value.toString())));
                        }
                    }
                    break;
                }
            }
        }
        return rebateInfo;
    }
}
